package com.lanou.service.impl;

import com.lanou.entity.SearchItem;
import com.lanou.entity.SearchResult;
import com.lanou.service.SearchItemService;
import com.lanou.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class SearchItemServiceImpl implements SearchItemService {

    @Value("${SEARCH_ITEM_JSON_URL}")
    private String SEARCH_ITEM_JSON_URL;


    @Override
    public SearchResult searchItemList(String query, Integer page, Integer rows) {
        SearchResult searchResult = HttpClientUtils.getObject(SEARCH_ITEM_JSON_URL + "?keyword=" + query + "&page=" + page + "&rows=" + rows, SearchResult.class);
        List<SearchItem> documents = searchResult.getDocuments();
        List<SearchItem> searchItemList = new ArrayList<>();
        for (SearchItem document : documents) {
            SearchItem searchItem = new SearchItem(document.getId(),
                    document.getTitle(),
                    document.getSell_point(),
                    document.getPrice(),
                    document.getImage().split(",")[0],
                    document.getCid(),
                    document.getCat(),
                    document.getItem_desc());
            searchItemList.add(searchItem);

        }
        searchResult.setDocuments(searchItemList);
        return searchResult;
    }
}
